package bzapps.weynak.fb;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import bzapps.weynak.Maps;
import bzapps.weynak.R;
import bzapps.weynak.fb.SessionEvents.AuthListener;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class FbClient extends Activity {

	public static final String APP_ID = "119791898115838";
	private static final String[] PERMISSIONS = new String[] {"publish_stream", "read_stream", "offline_access"};
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	public String uid = null;
	
	public String IP = "http://www.bz-apps.com/weynak";
	public String URL_LOGIN = "/authent.php?log_in=logmein";
	public String URL_FRIENDS = "/friends.php?manage_friends=update_friends";
	
	private SessionListener mSessionListener = new SessionListener();
	private SharedPreferences pref;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (APP_ID == null) {
			Util.showAlert(this, "Warning",	"Facebook Applicaton ID must be set...");
		}
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main);
		
		pref = PreferenceManager.getDefaultSharedPreferences(this);
		// Initialize the Facebook session
		mFacebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);
		SessionEvents.addAuthListener(mSessionListener);
		login();
	
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("WEYNAK.FB", "onActivityResult(): " + requestCode);
		mFacebook.authorizeCallback(requestCode, resultCode, data); 
	}

	public class IdRequestListener extends BaseRequestListener{

		@Override
		public void onComplete(String response, Object state) {		    
			        Log.d("WEYNAK.Friends Request", "response.length(): " + response.length());
			        Log.d("WEYNAK.Friends Request", "Response: " + response);
			        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
			        nvp.add(new BasicNameValuePair("credentials",response));
		    	try{
	    	        HttpClient httpclient = new DefaultHttpClient();
	    	        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
	    	        HttpPost httppost = new HttpPost(IP+ URL_LOGIN);
	    	        httppost.setEntity(new UrlEncodedFormEntity(nvp));
	    	        HttpResponse resp = httpclient.execute(httppost);
	    	        String id = EntityUtils.toString(resp.getEntity());
	    	        if (resp.getStatusLine().getStatusCode()==200)
	    	        {
	    	        	SaveId(id);
	    	        	mAsyncRunner.request("me/friends&fields=id", new FriendsRequestListener());	
	    	        }
	    	        Log.d("WEYNAK.return_statement",id);
	    	        Log.d("WEYNAK.query", response);
	    	        Log.d("WEYNAK.authent_state", String.valueOf(resp.getStatusLine().getStatusCode()));
	    	        
	    	}catch(Exception e){
	    	        Log.e("WEYNAK", "Error in http connection "+e.toString());    	        
	    	}
		}

		@Override
		public void onFacebookError(FacebookError e) {
			
		}

		
	}
	
	public class FriendsRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(String response, Object state) {
		    try {
		        Log.d("WEYNAK.Friends Request", "response.length(): " + response.length());
		        Log.d("WEYNAK.Friends Request", "Response: " + response);
		        final JSONObject json = new JSONObject(response);
		        JSONArray d = json.getJSONArray("data");
		        String friends = d.toString();	
		        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
		        nvp.add(new BasicNameValuePair("friends",friends));
		        nvp.add(new BasicNameValuePair("uid", uid));
		        Log.d("WEYNAK.friends",friends);
	    	try{
    	        HttpClient httpclient = new DefaultHttpClient();
    	        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
    	        HttpPost httppost = new HttpPost(IP+ URL_FRIENDS);
    	        httppost.setEntity(new UrlEncodedFormEntity(nvp));
    	        HttpResponse resp = httpclient.execute(httppost);
    	        if (resp.getStatusLine().getStatusCode()==200)
    	        {
    	        	Intent i = new Intent(getApplicationContext(), Maps.class);
    	        	finish();
    	        	startActivity(i);
    	        }
    	        Log.d("WEYNAK.query", friends);
    	        Log.d("WEYNAK.authent_state", String.valueOf(resp.getStatusLine().getStatusCode()));
    	        
    	}catch(Exception e){
    	        Log.e("WEYNAK", "Error in http connection "+e.toString());
    	        
    	}
		        
		    } catch (JSONException e) {
		        Log.w("WEYNAK.Facebook", "JSON Error in response");
		    }
		}

		@Override
		public void onFacebookError(FacebookError e) {

		}
	}

	private final class LoginDialogListener extends BaseDialogListener {

		/**
		 * Called when the dialog has completed successfully
		 */
		public void onComplete(Bundle values) {
			Log.d("WEYNAK.FB", "LoginDialogListener.onComplete()");
			SessionEvents.onLoginSuccess();
			mAsyncRunner.request("me/&fields=id,first_name,last_name,gender,birthday,picture", new IdRequestListener());			
				}
	}

	private class LogoutRequestListener extends BaseRequestListener {

		@Override
		public void onFacebookError(FacebookError e) {
		}

		@Override
		public void onComplete(String response, Object state) {
			FbClient.this.runOnUiThread(new Runnable() {
				public void run() {
				}
			});
		}
	}

	public void login(){
		Log.d("1111111111111111111111","WEYNAAAAK login()");
		if (mFacebook.isSessionValid()) {
			AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(
					mFacebook);
			asyncRunner.logout(this.getBaseContext(),
					new LogoutRequestListener());
		} else {
			mFacebook.authorize(this, PERMISSIONS,
					new LoginDialogListener());
			
		}
	}
	
	public void SaveId(String id){
    	
		pref.edit().putString("uid", id).commit();
		uid=id;		
	}
	
	private class SessionListener implements AuthListener{

		@Override
		public void onAuthSucceed() {
			SessionStore.save(mFacebook, getBaseContext());	
		}

		@Override
		public void onAuthFail(String error) {
						
		}
	}
	
	@Override
	public void onAttachedToWindow() {
	    super.onAttachedToWindow();
	    Window window = getWindow();
	    window.setFormat(PixelFormat.RGBA_8888);
	}
}